package com.demo.edit.util;

import com.alibaba.fastjson.JSON;
import com.demo.edit.config.ServerConfig;
import com.saver.office.RegisterEntity;
import com.saver.office.RequestRegister;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
public class RedisRegister implements RequestRegister {

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private ServerConfig serverConfig;

    @Override
    public synchronized String register(String fileId, String fileName, String userId, Boolean readOnly) {
        RegisterEntity entity = new RegisterEntity();
        entity.setReadOnly(readOnly);
        entity.setFileName(fileName);
        entity.setCreateDate(new Date());
        entity.setUserId(userId);
        String jsonString = JSON.toJSONString(entity);
        String encode = Base64.encode(fileId.getBytes(StandardCharsets.UTF_8));
        //编辑
        if (!readOnly) {
            //关键字 + id base64编码 + 是否编辑
            String s = redisManager.get(serverConfig.getKey() + encode + "_false");
            //并发问题,但一个用户已经在编辑一个指定id的文件时，其他用户只能够只读文件，不能上传文件
            if (s == null) {
                //当前文件未被占用,锁定当前文件
                redisManager.set(serverConfig.getKey() + encode + "_false", jsonString, 1800);
            }
        } else {
            //文件只读
            redisManager.set(serverConfig.getKey() + encode + "_true", jsonString, 1800);
        }
        return "EditOffice://" + encode + "_" + readOnly;
    }

    @Override
    public RegisterEntity get(String fileId) {

        String json = redisManager.get(serverConfig.getKey() + fileId);
        if (json == null) {
            return null;
        }
        return JSON.parseObject(json, RegisterEntity.class);
    }

    @Override
    public void logout(String fileId) {
        redisManager.delete(serverConfig.getKey() + fileId);
    }

    @Override
    public void refresh(String s) {
        redisManager.expire(serverConfig.getKey() + s, 500);
    }

    @Override
    public String getCurrentUserId(String fileId) {
        RegisterEntity entity = this.get(fileId);
        if (entity == null) {
            return null;
        }
        return entity.getUserId();
    }

    @Override
    public void deleteExpire() {
    }
}
